<script lang="ts" setup>
import {getCurrentInstance, ref, h, VNode, onBeforeMount} from 'vue'
import {ElButton, ElTag} from 'element-plus'
import SvgIcon from '@/components/svg-icon/index.vue'
import {service} from "@/utils";
import DataTable from '@/components/data-table/index.vue';
import {Repository, FileDatabase} from './interface'
import EditFileRepository from './components/repository.vue'
import EditFileDatabase from './components/database.vue'
import BrowseFile from './components/browse.vue'
import MainPage from "@/layout/other/MainPage.vue";

defineOptions({name: 'FileSystem'});

const dataTableRef = ref<Array<InstanceType<typeof DataTable>>>(); // 由于tab-pane是动态循环，所以会有多个
const browseFileRef = ref<InstanceType<typeof BrowseFile>>();
const editFileDatabaseRef = ref<InstanceType<typeof EditFileDatabase>>();
const editFileRepositoryRef = ref<InstanceType<typeof EditFileRepository>>();

const {proxy} = getCurrentInstance() as any;

const active = ref('1');
const loading = ref(false);
const defaultFileDatabaseId = ref('');
const repositories = ref<Repository[]>([]);
const params = ref({
    name: undefined
})
const columns =ref([
    {
        label: '名称',
        prop: 'name',
        width: 150,
        fixed: 'left',
        sortable: true,
    },
    {
        label: '状态',
        prop: 'currentFolderId',
        width: 90,
        align: 'center',
        render: ({row}: any) => {
            let isUse = defaultFileDatabaseId.value === row.id;
            return h(ElTag, { effect: "light", round: true, type: isUse? 'success':'info'}, {default: ()=> isUse? '已使用':'未使用'})
        }
    },
    {
        label: '存储路径',
        prop: 'path',
        minWidth: 250,
        tooltip: true,
    },
    {
        label: '存储目录',
        prop: 'currentFolderName',
        width: 150,
        tooltip: true,
        align: 'center',
        render: ({row}: any) => {
            return h('span', {}, {default: () => row['currentFolderName']? row['currentFolderName']:'尚未绑定'})
        }
    },
    {
        label: '阈值',
        prop: 'maxLimit',
        align: 'right',
        width: 100,
    },
    {
        label: '描述',
        prop: 'description',
        width: 300,
        tooltip: true,
    },
    {
        label: '创建时间',
        prop: 'createTime',
        width: 180,
        sortable: true
    },
    {
        type: 'action',
        width: 180,
        maxCollapseButtons: 3,
        render: ({row}: any) =>{
            const button: VNode[] = [];
            button.push(h(ElButton, {type: 'primary', link: true, onClick: ()=> onEdit('browse', row)}, {default: () => '查看'}))
            if (proxy.$auth('fileDatabase:update')){
                button.push(h(ElButton, {type: 'primary', link: true, onClick: ()=> onEdit('fileDatabase', row)}, {default: () => '编辑'}))
            }
            if (proxy.$auth('fileDatabase:delete')){
                button.push(h(ElButton, {type: 'danger',  link: true, onClick: ()=> onDeleteFileDatabase(row)}, {default: () => '删除'}))
            }
            return h('div', {}, button)
        }
    },
]);

function initRepositoryTab () {
    loading.value = true;
    service.get('/fileSystem/repository').then(({data}) => {
        if (data) {
            if (repositories.value.length) {
                repositories.value[0] = data;
            } else {
                repositories.value.push(data);
            }
            active.value = data.id;
            defaultFileDatabaseId.value = data.defaultFileDatabaseId;
        }
    }).finally(() => loading.value = false)
}
        
function onEdit (type: string, row?: FileDatabase) {
    switch (type) {
        case 'fileRepository':
            editFileRepositoryRef.value?.open({
                data: repositories.value[0],
                confirm: (resolve: (value: any)=> void, form: any) => {
                    service.post('/fileSystem/repository', form).then(({code}) => {
                        code === 200 && initRepositoryTab();
                        resolve(code)
                    })
                }
            });
            break;
        case 'fileDatabase':
            editFileDatabaseRef.value?.open({
                data: row,
                confirm: (resolve: (value: any)=> void, form: any, operate: AxiosMethod) => {
                    service[operate]('/fileSystem/fileDatabase', form).then(({code}) => {
                        code === 200 &&  dataTableRef.value?.[0]?.refresh();
                        resolve(code)
                    })
                }
            });
            break;
        case 'browse':
            browseFileRef.value?.open(row);
            break;
    }
}
        
function onDeleteFileDatabase (row: any) {
    service.confirm(`确定删除文件库【${row.name}】,包括所有目录及其文件且无法恢复?`, {
        url: '/fileSystem/fileDatabase',
        data: {id: row.id},
        success: () => dataTableRef.value?.[0]?.refresh()
    })
}

onBeforeMount(() => initRepositoryTab())

</script>
<template>
    <main-page>
        <div class="file-system" id="fileSystem">
            <el-tabs v-model="active" type="card" v-loading="loading">
                <el-tab-pane v-for="repository in repositories" :key="repository.id" :label="repository.name" :name="repository.id" style="height: 100%">
                    <data-table ref="dataTableRef" :columns="columns" :params="params" :offset-height="55" :pagination="true" api="/fileSystem/fileDatabase">
                        <template #button>
                            <el-button v-auth="'fileRepository:edit'" @click="onEdit('fileRepository')" />
                            <el-button v-auth="'fileDatabase:add'"  @click="onEdit('fileDatabase')"/>
                        </template>
                        <template #search>
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="params.name"/>
                            </el-form-item>
                        </template>
                    </data-table>
                </el-tab-pane>
<!--                <el-empty v-if="!repositories.length">-->
<!--                    <template #description>-->
<!--                        <span>点击右上角&nbsp;&nbsp;</span>-->
<!--                        <el-icon>-->
<!--                            <svg-icon icon="icon-setting"/>-->
<!--                        </el-icon>-->
<!--                        <span>&nbsp;初始化文件仓信息（注：文件仓只能创建一次）</span>-->
<!--                    </template>-->
<!--                </el-empty>-->
            </el-tabs>

            <edit-file-repository ref="editFileRepositoryRef"/>
            <edit-file-database ref="editFileDatabaseRef"/>
            <browse-file ref="browseFileRef"/>
        </div>
    </main-page>
</template>
<style lang="scss" scoped>
.file-system {
    height: 100%;
    padding: 5px;

    .el-tabs__new-tab{
        border: unset;
        width: unset;
    }

    .item {
        margin-top: 5px;
    }

    .el-badge__content.is-fixed {
        right: -5px;
        top: 5px
    }

    .el-tabs--top{
        height: 100%;
    }

    :deep(.el-tabs__header) {
        margin-bottom: 0;
    }
}
</style>